package org.kl.bf.service.basic;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.OperateLogs;
import org.kl.bf.repository.basic.OperateLogsDao;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:11:30
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class OperateLogsService {

	private OperateLogsDao operateLogsDao;

	public OperateLogs getOperateLogs(String id) {
		return operateLogsDao.findOne(id);
	}

	public void saveOperateLogs(OperateLogs entity) {
		operateLogsDao.save(entity);
	}

	public void deleteOperateLogs(String guid) {
		operateLogsDao.delete(guid);
	}

	public Page<OperateLogs> getUserOperateLogs(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<OperateLogs> spec = buildSpecification(searchParams);

		return operateLogsDao.findAll(spec, pageRequest);
	}
	public String multiDelete(String ids) {
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for (String id : idArray) {
			if (StringUtils.isNotBlank(id)) {
				operateLogsDao.delete(id);
				i++;
			}
		}
		return "删除" + i + "条记录";
	}
	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<OperateLogs> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<OperateLogs> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), OperateLogs.class);
		return spec;
	}

	@Autowired
	public void setOperateLogsDao(OperateLogsDao operateLogsDao) {
		this.operateLogsDao = operateLogsDao;
	}

	public List<OperateLogs> getAllUserOperateLogs(Map<String, Object> searchParams, String sortType, String orderType) {
		Specification<OperateLogs> spec = KLDynamicSpecifications.buildSpecification(searchParams, OperateLogs.class);
		return operateLogsDao.findAll(spec, CRUDUtils.buildSort(sortType, orderType));
	}

}
